package com.iterator.service.web.systemManager;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iterator.bean.web.wy.storage.Storage;
import com.iterator.bean.web.wy.storage.StorageExample;
import com.iterator.bean.web.wy.storage.StorageVO;
import com.iterator.bean.web.wy.storage.UpdateStorageVO;
import com.iterator.mapper.web.systemManager.StorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: Silence_W
 * @date: 2021-01-10 17:10
 **/
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;

    @Override
    public StorageVO queryStorage(Integer page, Integer limit, String key, String name, String sort, String order) {
        PageHelper.startPage(page, limit);
        StorageExample storageExample = new StorageExample();
        storageExample.setOrderByClause(sort + " " + order);
        StorageExample.Criteria criteria = storageExample.createCriteria();
        if (key != null&&key.length()!=0) {
            criteria.andKeyLike("%" + key + "%");
        }
        if (name != null&&name.length()!=0) {
            criteria.andNameLike("%" + name + "%");

        }
        List<Storage> storages = storageMapper.selectByExample(storageExample);
        PageInfo<Storage> storagePageInfo = new PageInfo<>(storages);
        int total = (int) storagePageInfo.getTotal();

        return new StorageVO(total, storages);
    }

    @Value("${file.winpath}")
    String winPath;

    @Value("${file.macpath}")
    String macPath;

    @Value("${file.prefixUrl}")
    String prefixUrl;

    @Override

    public Storage create(MultipartFile file, HttpServletRequest request) {
        //获取源文件名
        String originalFilename = file.getOriginalFilename();
        //获取源文件内容的类型
        String contentType = file.getContentType();
        //获取文件大小
        int size = (int) file.getSize();
        //获取插入时间
        Date date = new Date();

        //获取文件名key
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //从原文件名中获取文件后缀，eg:1.png——>.png
        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
        String key = uuid + s;

        //获取访问图片的url
        String url = prefixUrl + key;

        //文件上传逻辑：首先判断文件夹是否存在
        String path = null;
        String header = request.getHeader("User-Agent");
        if (header.contains("Windows")){
            path = winPath;
        } else if (header.contains("Mac")){
            path = macPath;
        }
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //上传文件
        try {
            file.transferTo(new File(path, key));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //更新数据库记录
        Storage storage = new Storage(null, key, originalFilename,
                contentType, size, url, date, date, false);
        int i = storageMapper.insertSelective(storage);
        if (i != 0) {
            return storage;
        }
        return null;
    }

    //对象存储的编辑
    @Override
    @Transactional
    public UpdateStorageVO updateStorage(Storage storage) {

        storage.setUpdateTime(new Date());
        int i = storageMapper.updateByPrimaryKey(storage);
        return new UpdateStorageVO(storage.getId(),storage.getKey(),storage.getName(),storage.getType(),storage.getSize(),storage.getUrl(),storage.getAddTime().toString(),storage.getUpdateTime().toString());
    }

    //对象存储的删除
    @Override
    public void delete(Integer id) {
    storageMapper.deleteByPrimaryKey(id);
    }


}
